package com.pupil.down.thread;

import com.pupil.down.system.SysSettings;

import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description: 日志线程
 * @Author: pupil
 * @Date: 2024/09/28 下午 3:54
 */
public class LogThread implements Callable<Boolean> {

    // 本地已经完成的下载大小
    public static AtomicLong LOCAL_FINISH_SIZE = new AtomicLong();

    // 文件下载大小
    public static AtomicLong DOWNLOAD_SIZE = new AtomicLong();

    // 完成下载的线程数
    public static AtomicLong DOWNLOAD_FINISH_THREAD = new AtomicLong();

    // 文件单位（MB）
    private static double UNIT = 1024d * 1024d;

    // 网络文件长度
    private long httpFileContentLength;

    public LogThread(long httpFileContentLength) {
        this.httpFileContentLength = httpFileContentLength;
    }

    @Override
    public Boolean call() throws Exception {
        // 用于记录过去5秒内每次迭代时的下载大小变化
        int[] downSizeArr = new int[5];
        int i = 0;
        // 记录上次的已经下载的文件大小
        double size = 0;
        // 文件总大小
        String httpFileSize = String.format("%.2f", httpFileContentLength / UNIT);
        while (DOWNLOAD_FINISH_THREAD.get() != SysSettings.DOWNLOAD_THREAD_NUM) {
            double downloadSize = DOWNLOAD_SIZE.get();
            // 计算本次下载的文件大小存储在downSizeArr中
            downSizeArr[++i % 5] = Double.valueOf(downloadSize - size).intValue();
            size = downloadSize;

            // 每秒速度
            double fiveSecDownloadSize = Arrays.stream(downSizeArr).sum();
            int speed = (int) ((fiveSecDownloadSize / 1024d) / (i < 5d ? i : 5d));

            //剩余时间
            double surplusSize = httpFileContentLength - downloadSize - LOCAL_FINISH_SIZE.get();
            String surplusTime = String.format("%.1f", surplusSize / 1024d / speed);
            // 如果剩余时间无穷大则显示未知符号
            if (surplusTime.equals("Infinity")) {
                surplusTime = "-";
            }

            //已下载大小
            String currentFileSize = String.format("%.2f", downloadSize / UNIT + LOCAL_FINISH_SIZE.get() / UNIT);

            String speedLog = String.format("> 已下载 %smb/%smb,速度 %skb/s,剩余时间 %ss", currentFileSize, httpFileSize, speed, surplusTime);
            System.out.print("\r");
            System.out.print(speedLog);
            Thread.sleep(1000);
        }
        System.out.println();
        return true;
    }
}
